const app = getApp()
const util = require('../../utils/util')

Page({
    data: {
        // userName: getApp().data.userName,
        fabu: '/icon/fabu.png',
        fenxiang: '/icon/fenxiang.png',
        weizhi_tu: '/icon/find_weizhi.png',
        touxiang: '/icon/touxiang.png',
        city: getApp().data.localCity
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    //点击跳转至文章详情页
    gotoDetail: function (e) {
        let item = e.currentTarget.dataset.item
        wx.cloud.database().collection('tiezi').where({ _id: item._id }).get({
            success: res=>{
                wx.navigateTo({
                    url: `/pages/tieziDetail/tieziDetail?_id=${res.data[0]._id}`,
                })
            }
        })
    },


    like: function (e) {
        let item = e.currentTarget.dataset.item
        const that = this

        // 获取帖子的count与collect（收藏与否）
        wx.cloud.database().collection('tiezi').where({ _id: item._id }).get({
            success: res => {
                const data = res.data[0]
                console.log('data',data)
                console.log(data.isDianzan);
                const id = item._id;
                console.log(id);
                if (data.isDianzan == 'false') {
                    console.log('xihuan')
                    // 改变collect属性
                    wx.cloud.database().collection('tiezi').doc(id).update({
                        data: {
                            isDianzan: 'true',
                            dianzan: '/icon/yidianzan.png',
                            dianzaned: '已点赞'
                        },
                        success:res=>{
                            console.log(data);
                            console.log('collect2');
                            wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc').get({
                                success: res=>{
                                    console.log(res.data);
                                    that.setData({
                                        list: res.data,
                                    })
                                },
                                fail(res) {
                                    console.log("请求失败", res)
                                }
                            })
                        },
                        fail:res=>{
                            console.log('shibai1')
                        }
                    })
                    // 点赞
                if (data.isDianzan == 'false') {
                    console.log('xihuan')
                    console.log(data._userName,data._id,data.reci,new Date().toLocaleString())
                    wx.cloud.callFunction({
                        name: 'update',
                        data: {
                            user: getApp().data.userName,    //点赞者名字
                            userimg:getApp().data.userImg,  //点赞者头像
                            _openid: data._openid,         //帖子发布者id
                            _id: data._id,            //帖子id 
                            message:'点赞'
                        }, success: function (res) {
                            console.log('success：',res)
                        }, fail: function (res) {
                            console.log('err',res)
                        }      
                    })
                }
                    
                    
                    //增加数据到我的喜欢里
                    wx.cloud.database().collection('mylike').add({
                        data: {
                            touxiang: item.touxiang,
                            nicheng: item.nicheng,
                            content: item.desc,
                            images: item.fileIDs,
                            createTime: item.createTime,
                            date: item.date,
                            reci: item.reci,
                            id: item._id,
                            isDianzan: 'true'
                        },
                        success:res=>{
                            console.log(item);
                            console.log('add after')
                        },
                        fail:res=>{
                            console.log('shibai')
                        }
                    })
                //取消喜欢 
                } else if(data.isDianzan == 'true'){
                    console.log('quxiaoxihuan')
                    // 改变collect属性
                    wx.cloud.database().collection('tiezi').doc(id).update({
                        data: {
                            isDianzan: 'false',
                            dianzan: '/icon/dianzan.png',
                            dianzaned: '点赞'
                        },
                        success:res=>{
                            console.log('quxiaochenggong');
                            wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc').get({
                                success(res) {
                                    console.log(res.data);
                                    that.setData({
                                        list: res.data,
                                    })
                                },
                                fail(res) {
                                    console.log("请求失败", res)
                                }
                            })
                        },
                        fail:res=>{
                            console.log('quxiaoshibai')
                        }
                    })
                    // 从我的喜欢列表移除
                    wx.cloud.database().collection('mylike').where({id:item._id}).remove({
                        success:res=>{
                            console.log('yichuchenggong')
                        },
                        fail:res=>{
                            console.log('yichushibai')
                        }
                    })
                }else{
                    console.log(data.isDianzan)
                }

            },
            fail:res=>{
                console.log(res.message)
            }
        })
    },

    shoucang: function (e) {
        let item = e.currentTarget.dataset.item
        const that = this

        // 获取帖子的count与collect（收藏与否）
        wx.cloud.database().collection('tiezi').where({ _id: item._id }).get({
            success: res => {
                const data = res.data[0]
                console.log('data',data)
                console.log(data.isCollect);
                const id = item._id;
                if (data.isCollect == 'false') {
                    console.log('shoucang')
                    // 改变collect属性
                    wx.cloud.database().collection('tiezi').doc(id).update({
                        data: {
                            isCollect: 'true',
                            collect: '/icon/yishoucang.png',
                            collected: '已收藏'
                        },
                        success:res=>{
                            console.log(data);
                            console.log('collect2');
                            wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc').get({
                                success(res) {
                                    console.log(res.data);
                                    that.setData({
                                        list: res.data,
                                    })
                                },
                                fail(res) {
                                    console.log("请求失败", res)
                                }
                            })
                        },
                        fail:res=>{
                            console.log('shibai1')
                        }
                    })
                    if (data.isCollect == 'false') {
                        console.log('shoucang')
                        console.log(data._userName,data._id,data.reci,new Date().toLocaleString())
                        wx.cloud.callFunction({
                            name: 'update',
                            data: {
                                user: getApp().data.userName,    //点赞者名字
                                userimg:getApp().data.userImg,  //点赞者头像
                                _openid: data._openid,         //帖子发布者id
                                _id: data._id,            //帖子id 
                                message:'收藏'
                            }, success: function (res) {
                                console.log('success：',res)
                            }, fail: function (res) {
                                console.log('err',res)
                            }      
                        })
                    }
                    //增加数据到我的喜收藏里
                    wx.cloud.database().collection('mycollect').add({
                        data: {
                            touxiang: item.touxiang,
                            nicheng: item.nicheng,
                            content: item.desc,
                            images: item.fileIDs,
                            createTime: item.createTime,
                            date: item.date,
                            reci: item.reci,
                            id: item._id,
                            isCollect: 'true'
                        },
                        success:res=>{
                            console.log(item);
                            console.log('add after')
                        },
                        fail:res=>{
                            console.log('shibai')
                        }
                    })
                //取消收藏 
                } else if(data.isCollect == 'true'){
                    console.log('quxiaoxihuan')
                    // 改变collect属性
                    wx.cloud.database().collection('tiezi').doc(id).update({
                        data: {
                            isCollect: 'false',
                            collect: '/icon/shoucang_2.png',
                            collected: '收藏'
                        },
                        success:res=>{
                            console.log('quxiaochenggong');
                            wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc').get({
                                success(res) {
                                    console.log(res.data);
                                    that.setData({
                                        list: res.data,
                                    })
                                },
                                fail(res) {
                                    console.log("请求失败", res)
                                }
                            })
                        },
                        fail:res=>{
                            console.log('quxiaoshibai')
                        }
                    })
                    // 从我的收藏列表移除
                    wx.cloud.database().collection('mycollect').where({id:item._id}).remove({
                        success:res=>{
                            console.log('yichuchenggong')
                        },
                        fail:res=>{
                            console.log('yichushibai')
                        }
                    })
                }else{
                    console.log(data.isCollect)
                }

            },
            fail:res=>{
                console.log(res.message)
            }
        })
    },

    fenxiang: function(e){
        let item = e.currentTarget.dataset.item
        const that = this

        wx.cloud.database().collection('tiezi').where({ _id: item._id }).get({
            success: res=>{
                console.log(res.data);
                wx.cloud.database().collection('myfabu').add({
                    data: {
                        date: util.formatDate(new Date()),
                        createTime:new Date().toLocaleString(),
                        reci: res.data[0].reci,
                        desc: res.data[0].desc,
                        images: res.data[0].images,
                    },
                })
                wx.cloud.database().collection('tiezi').add({
                    data: {
                        createTime:new Date().toLocaleString(),
                        fileIDs: res.data[0].fileIDs,
                        date: util.formatDate(new Date()),
                        touxiang: app.data.userImg,
                        nicheng: app.data.userName,
                        city: app.data.localCity,
                        reci: res.data[0].reci,
                        desc: res.data[0].desc,
                        images: res.data[0].images,
                        isDianzan: 'false',
                        dianzan: '/icon/dianzan.png',
                        dianzaned: '点赞',
                        isCollect: 'false',
                        collect: '/icon/shoucang_2.png',
                        collected: '收藏'
                    },
                    success: res => {
                        wx.hideLoading()
                        wx.showToast({
                            title: '分享成功',
                        })
                        console.log('分享成功', res)
                        wx.switchTab({
                            url: '/pages/find/find',
                        })
                        wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc').get({
                            success(res) {
                                console.log(res.data);
                                that.setData({
                                    list: res.data,
                                })
                            },
                            fail(res) {
                                console.log("请求失败", res)
                            }
                        })
                    },
                    fail: err => {
                        wx.hideLoading()
                        wx.showToast({
                            icon: 'none',
                            title: '网络不给力....'
                        })
                        console.error('分享失败', err)
                    }
                })
            }
        })
    },

    delete: function(e){
        let item = e.currentTarget.dataset.item
        const that = this

        wx.cloud.database().collection('tiezi').where({ _id: item._id }).get({
            success: res=>{
                console.log(res.data);
                const id = item._id;
                const tieList = res.data;
                console.log(id);
                wx.cloud.database().collection('myfabu').get({
                    success: res=>{
                        console.log(res.data)
                        wx.cloud.database().collection('myfabu').where({
                            _id: ()=>{res.data.map(item=>{
                                if(item.createTime==tieList[0].createTime){
                                    return item._id
                                }
                            })}
                        }).remove({
                            success: res=>{
                                console.log(res.data);
                                console.log("我的发布页删除成功")
                            }
                        })
                    }
                })
                wx.cloud.database().collection('tiezi').doc(id).remove({
                    success: res => {
                        console.log('发现页面删除成功')
                        wx.switchTab({
                            url: '/pages/find/find',
                        })
                        wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc').get({
                            success(res) {
                                console.log(res.data);
                                that.setData({
                                    list: res.data,
                                })
                            },
                            fail(res) {
                                console.log("请求失败", res)
                            }
                        })
                    },
                    fail: err => {
                        console.error('删除失败', err)
                    }
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            city: getApp().data.localCity,
            userName: getApp().data.userName
        })
        console.log(getApp().data.userName);
        const that = this
        wx.cloud.database().collection('tiezi').orderBy('createTime', 'desc') //按发布视频排序
        .get({
            success(res) {
                console.log(res.data);
                that.setData({
                    list: res.data,
                })
            },
            fail(res) {
                console.log("请求失败", res)
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})